package com.zbkj.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.service.PieceService;
import com.zbkj.common.model.client.workbench.IntoPieces;
import com.zbkj.common.model.client.workbench.VideoTemplateFinal;
import com.zbkj.common.request.client.BatchDeleteRequest;
import com.zbkj.common.result.CommonResult;
import com.zbkj.service.service.IntoPiecesService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/client/assets")
public class PieceController {

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private IntoPiecesService intoPiecesService;

    @Autowired
    private PieceService pieceService;

    /**
     * 获取模板视频列表-成片列表
     * @param page
     * @param pageSize
     * @param httpRequest
     * @return
     */
    @GetMapping("/getPieceList")
    public CommonResult<IPage<IntoPieces>> getPieceList(@RequestParam(value = "page", defaultValue = "1") int page,
                                                                        @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
                                                                        @RequestParam(value = "parentId", required = false) Integer parentId,
                                                                        HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        Page<IntoPieces> pageParam = new Page<>(page, pageSize);
        QueryWrapper<IntoPieces> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .eq("user_id", userId)
                .orderByDesc("create_time");

        Integer parId = parentId != null ? parentId : 0;
        wrapper.eq("parent_id", parId);

        IPage<IntoPieces> res = intoPiecesService.page(pageParam, wrapper);

        return CommonResult.success(res);
    }

    /**
     * 获取模板视频详情
     * @param id
     * @return
     */
    @GetMapping("/getPieceDetail")
    public CommonResult<IntoPieces> getPieceDetail(@RequestParam(value = "id", required = false) int id,
                                                                   HttpServletRequest httpRequest) {
        IntoPieces byId = intoPiecesService.getById(id);
        return CommonResult.success(byId);
    }

    @ApiOperation(value = "批量删除生成的视频模板（软删除）")
    @PostMapping("/delPiece")
    public CommonResult<Map<String, Object>> delPiece(@RequestBody BatchDeleteRequest request, HttpServletRequest httpRequest) {
        List<Integer> ids = request.getIds();
        if (ids == null || ids.isEmpty()) {
            return CommonResult.failed("请选择要删除的视频");
        }

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }

        // 校验所有id对应的记录
        for (Integer id : ids) {
            IntoPieces intoPieces = intoPiecesService.getById(id);
            if (intoPieces == null || intoPieces.getIsDel() == null || intoPieces.getIsDel() != 0) {
                return CommonResult.failed("视频ID " + id + " 不存在或已被删除");
            }
            if (!userId.equals(intoPieces.getUserId())) {
                return CommonResult.failed("无权操作素材ID " + id);
            }
        }

        boolean result = pieceService.batchDelVideo(ids);
        Map<String, Object> data = new HashMap<>();
        data.put("result", result ? 1 : 0);
        return CommonResult.success(data);
    }
}
